package com.offics.loan.domain.service;

import com.offics.loan.domain.entity.BankCard;
import com.offics.loan.domain.repository.BankCardRepository;
import com.offics.loan.domain.repository.UserRepository;
import com.offics.loan.infrastructure.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 银行卡领域服务
 */
@Service
@RequiredArgsConstructor
public class BankCardDomainService {

    private final BankCardRepository bankCardRepository;
    private final UserRepository userRepository;

    /**
     * 添加银行卡
     *
     * @param void 银行卡
     * @return 添加后的银行卡
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean add(BankCard bankCard) {
        // 检查用户是否存在
        if (!userRepository.findById(bankCard.getUserId()).isPresent()) {
            throw new BusinessException("用户不存在");
        }

        // 检查银行卡号是否存在
        if (bankCardRepository.existsByCardNo(bankCard.getCardNo())) {
            throw new BusinessException("银行卡号已存在");
        }

        // 检查是否有默认银行卡
        List<BankCard> bankCards = bankCardRepository.findByUserId(bankCard.getUserId());
        if (bankCards.isEmpty()) {
            // 如果没有银行卡，则设置为默认
            bankCard.setIsDefault(1);
        } 
        // 如果设置为默认，保存后会在save方法之后处理默认状态

        // 设置状态为启用
        bankCard.setStatus(1);
        boolean saved = bankCardRepository.save(bankCard);
        
        // 如果保存成功且设置为默认卡，则更新默认状态
        if (saved && bankCard.getIsDefault() != null && bankCard.getIsDefault() == 1) {
            // 使用仓储的setDefault方法一次性更新所有银行卡的默认状态
            bankCardRepository.setDefault(bankCard.getId(), bankCard.getUserId());
        }
        return saved;
    }

    /**
     * 更新银行卡
     *
     * @param bankCard 银行卡
     * @return 是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean update(BankCard bankCard) {
        // 检查银行卡是否存在
        Optional<BankCard> optionalBankCard = bankCardRepository.findById(bankCard.getId());
        if (optionalBankCard.isEmpty()) {
            throw new BusinessException("银行卡不存在");
        }

        BankCard existingBankCard = optionalBankCard.get();

        // 检查银行卡号是否存在
        if (!existingBankCard.getCardNo().equals(bankCard.getCardNo()) && bankCardRepository.existsByCardNo(bankCard.getCardNo())) {
            throw new BusinessException("银行卡号已存在");
        }

        // 保存银行卡信息
        boolean updated = bankCardRepository.update(bankCard);
        
        // 检查是否设置为默认
        if (updated && bankCard.getIsDefault() != null && bankCard.getIsDefault() == 1 && 
            (existingBankCard.getIsDefault() == null || existingBankCard.getIsDefault() != 1)) {
            // 如果设置为默认，使用仓储的setDefault方法一次性更新所有银行卡的默认状态
            bankCardRepository.setDefault(bankCard.getId(), existingBankCard.getUserId());
        }

        return updated;
    }

    /**
     * 删除银行卡
     *
     * @param id 银行卡ID
     * @return 是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        // 检查银行卡是否存在
        Optional<BankCard> optionalBankCard = bankCardRepository.findById(id);
        if (optionalBankCard.isEmpty()) {
            throw new BusinessException("银行卡不存在");
        }

        BankCard bankCard = optionalBankCard.get();

        // 如果是默认银行卡，则设置其他银行卡为默认
        if (bankCard.getIsDefault() != null && bankCard.getIsDefault() == 1) {
            List<BankCard> bankCards = bankCardRepository.findByUserId(bankCard.getUserId());
            for (BankCard card : bankCards) {
                if (!card.getId().equals(id)) {
                    card.setIsDefault(1);
                    bankCardRepository.update(card);
                    break;
                }
            }
        }

        return bankCardRepository.deleteById(id);
    }

    /**
     * 设置默认银行卡
     *
     * @param id     银行卡ID
     * @param userId 用户ID
     * @return 是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean setDefault(Long id, Long userId) {
        // 检查银行卡是否存在
        Optional<BankCard> optionalBankCard = bankCardRepository.findById(id);
        if (optionalBankCard.isEmpty()) {
            throw new BusinessException("银行卡不存在");
        }

        BankCard bankCard = optionalBankCard.get();

        // 检查银行卡是否属于该用户
        if (!bankCard.getUserId().equals(userId)) {
            throw new BusinessException("银行卡不属于该用户");
        }

        return bankCardRepository.setDefault(id, userId);
    }

    /**
     * 启用银行卡
     *
     * @param id 银行卡ID
     * @return 是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean enable(Long id) {
        // 检查银行卡是否存在
        Optional<BankCard> optionalBankCard = bankCardRepository.findById(id);
        if (optionalBankCard.isEmpty()) {
            throw new BusinessException("银行卡不存在");
        }

        BankCard bankCard = optionalBankCard.get();
        bankCard.setStatus(1);
        return bankCardRepository.update(bankCard);
    }

    /**
     * 禁用银行卡
     *
     * @param id 银行卡ID
     * @return 是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean disable(Long id) {
        // 检查银行卡是否存在
        Optional<BankCard> optionalBankCard = bankCardRepository.findById(id);
        if (optionalBankCard.isEmpty()) {
            throw new BusinessException("银行卡不存在");
        }

        BankCard bankCard = optionalBankCard.get();

        // 如果是默认银行卡，则不能禁用
        if (bankCard.getIsDefault() != null && bankCard.getIsDefault() == 1) {
            throw new BusinessException("默认银行卡不能禁用");
        }

        bankCard.setStatus(0);
        return bankCardRepository.update(bankCard);
    }
}